{% load static tailwind_tags %}
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
    <title>匿名聊天室</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    {% tailwind_css %}

    <style>
        @keyframes gradientFlow {
            0% {
                background-position: 0% 50%;
            }
            50% {
                background-position: 100% 50%;
            }
            100% {
                background-position: 0% 50%;
            }
        }

        .animate-gradient {
            animation: gradientFlow 15s ease infinite;
        }
    </style>

</head>
<body class="min-h-screen relative overflow-hidden">
<!-- 背景层 -->
<div class="absolute inset-0 bg-gradient-to-r from-pink-300/40 via-purple-300/40 to-blue-300/40 animate-gradient bg-[length:200%_200%] blur-3xl"></div>

<!-- 页面内容 -->
<div class="relative z-10">


    <!-- 导航栏 -->
    <div class="navbar bg-base-200 shadow-lg">
        <div class="flex-1">
            <a class="btn btn-ghost text-xl">🥳 聊天室</a>
        </div>
        <div class="flex-none">


            <!-- 用户头像 -->
            {#        <div class="dropdown dropdown-end">#}
            {#            <div class="avatar">#}
            {#                <div class="w-12">#}
            {#                    <img id="userAvatar" src=""/>#}
            {#                </div>#}
            {#            </div>#}
            {#        </div>#}


            <!-- 用户头像 -->
            <div class="dropdown dropdown-end">

                <div tabindex="0" role="button" class="btn btn-ghost btn-circle avatar">
                    <div class="avatar">
                        <div class="w-12">
                            <img id="userAvatar" src=""/>
                        </div>
                    </div>
                </div>
                <ul tabindex="0"
                    class="menu menu-sm dropdown-content mt-3 z-[1] p-2 shadow bg-base-100 rounded-box w-52">
                    <fieldset>
                        <legend class="fieldset-legend">昵称</legend>
                        <div class="join">
                            <input id="username" type="text" value="匿名" class="input join-item"
                                   placeholder="请输入昵称"/>
                        </div>
                    </fieldset>

                </ul>
            </div>

        </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="container mx-auto max-w-6xl p-8">
        <div class="card bg-base-100 shadow-xl">
            <div class="card-body p-0">
                <!-- 聊天头部 -->
                <div class="bg-primary text-primary-content p-4 rounded-t-2xl">
                    <div class="flex items-center space-x-3">
                        <div class="avatar">
                            <div class="w-10 rounded-full bg-primary-content text-primary">
                                <div class="flex items-center justify-center w-full h-full">
                                    🦉
                                </div>
                            </div>
                        </div>
                        <div>
                            <h2 class="font-bold">聊天室</h2>
                            <p class="text-sm opacity-80" id="connection-status">连接中...</p>
                        </div>
                    </div>
                </div>

                <!-- 聊天消息区域 -->
                <div class="h-122 overflow-y-auto p-4 space-y-4" id="chat-messages">

                </div>

                <!-- 输入区域 -->
                <div class="p-4 border-t bg-base-50">
                    <div class="flex space-x-2">
                        <div class="flex-1">
                            <input
                                    type="text"
                                    placeholder="输入消息..."
                                    class="input input-bordered w-full"
                                    id="message-input"
                                    maxlength="500"
                            />
                        </div>
                        <button class="btn btn-primary" id="send-btn">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20"
                                 fill="currentColor">
                                <path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z"></path>
                            </svg>
                        </button>
                    </div>
                    <div class="text-xs text-base-content/60 mt-2">
                        按 Enter 发送消息
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 主题切换按钮 -->
    <div class="fixed bottom-4 right-4">
        <div class="dropdown dropdown-top dropdown-end">
            <div tabindex="0" role="button" class="btn btn-circle btn-outline">
                <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd"
                          d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z"
                          clip-rule="evenodd"></path>
                </svg>
            </div>
            <ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-32">
                <li><a onclick="setTheme('light')">🌤️ 浅色</a></li>
                <li><a onclick="setTheme('dark')">🌙 深色</a></li>
            </ul>
        </div>
    </div>

    <script>
        // WebSocket 连接
        let socket = null;
        const messageInput = document.getElementById('message-input');
        const sendBtn = document.getElementById('send-btn');
        const messagesContainer = document.getElementById('chat-messages');
        const connectionStatus = document.getElementById('connection-status');

        // 初始化 WebSocket 连接
        function initWebSocket() {

           // socket = new WebSocket("ws://127.0.0.1:8000/room/{{ num }}/")
socket = new WebSocket("ws://106.54.35.125:8001/room/{{ num }}/")
            socket.onopen = function (event) {
                console.log('WebSocket 连接已建立');
                connectionStatus.textContent = '已连接';
                connectionStatus.className = 'text-sm text-success';
            };

            socket.onmessage = function (event) {
                const data = JSON.parse(event.data);
                addMessage(data.message, data.username, data.ImgUrl);
            };


            socket.onclose = function (event) {
                console.log('WebSocket 连接已关闭');
                connectionStatus.textContent = '连接断开';
                connectionStatus.className = 'text-sm text-error';
                // 重连逻辑
                setTimeout(initWebSocket, 3000);
            };

            socket.onerror = function (error) {
                console.error('WebSocket 错误:', error);
                connectionStatus.textContent = '连接错误';
                connectionStatus.className = 'text-sm text-error';
            };
        }

        // 发送消息
        function sendMessage() {
            const message = messageInput.value.trim();
            if (message && socket && socket.readyState === WebSocket.OPEN) {
                // 添加用户消息到界面
                addMessage(message, '我', document.getElementById('userAvatar').src);

                // 发送到服务器
                socket.send(JSON.stringify({
                    'message': message,
                    'type': 'chat_message',
                    'url': document.getElementById('userAvatar').src,
                    'username': document.getElementById('username').value
                }));

                messageInput.value = '';
            }
        }

        // 添加消息到聊天界面
        function addMessage(message, user, ImgUrl) {
            console.log("addMessage", message);

            const isCurrentUser = user === '我';
            const positionClass = isCurrentUser ? 'chat-end' : 'chat-start';
            const bubbleClass = isCurrentUser ? 'chat-bubble-primary' : 'chat-bubble-secondary';

            const currentTime = new Date().toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
            });

            const messageDiv = document.createElement('div');
            messageDiv.className = `chat ${positionClass}`; // 控制左右对齐

            messageDiv.innerHTML = `
        <div class="chat-image avatar">
            <div class="w-10 rounded-full overflow-hidden">
                <img
                    src="${ImgUrl}"
                    alt="${escapeHtml(user)}'s avatar"
                    class="w-full h-full object-cover"
                    loading="lazy"
                    onerror="this.onerror=null; this.src='';"
                >
            </div>
        </div>
        <div class="chat-header">
            ${escapeHtml(user)}
            <time class="text-xs opacity-50" datetime="${new Date().toISOString()}">${currentTime}</time>
        </div>
        <div class="chat-bubble ${bubbleClass}">
            ${escapeHtml(message)}
        </div>
    `;

            messagesContainer.appendChild(messageDiv);
            // 平滑滚动到底部
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // HTML 转义函数
        function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // 主题切换
        function setTheme(theme) {
            document.documentElement.setAttribute('data-theme', theme);
            localStorage.setItem('theme', theme);
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function () {
            // 恢复主题设置
            const savedTheme = localStorage.getItem('theme') || 'light';
            setTheme(savedTheme);
            // 初始化 WebSocket
            initWebSocket();
            // 绑定事件
            sendBtn.addEventListener('click', sendMessage);

            messageInput.addEventListener('keypress', function (event) {
                if (event.key === 'Enter') {
                    event.preventDefault();
                    sendMessage();
                }
            });

            // 发起 HTTP GET 请求
            fetch('https://api.dwo.cc/api/s2tou') // 替换为你的 API 地址
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json(); // 解析 JSON 数据
                })
                .then(data => {
                    const imgElement = document.getElementById('userAvatar');
                    imgElement.src = data['数据']['pic']; // 动态替换图片

                    // 在这里处理返回的数据（例如更新 UI）
                })
                .catch(error => {
                    console.error('GET 请求失败:', error);
                });


        });
    </script>

</div>
</body>

</html>

